package com.zhongyi.http;


import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.zhongyi.entity.Company;
import com.zhongyi.entity.Contact;
import com.zhongyi.entity.SysLog;
import com.zhongyi.http.base.BaseAction;
import com.zhongyi.http.service.MailService;
import com.zhongyi.util.Constant;
import com.zhongyi.util.HttpUtil;
import com.zhongyi.util.Pager;
import com.zhongyi.util.StringUtil;
import com.zhongyi.util.UUIDGenerator;

public class MailAction extends BaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<Contact> mailList;
	private MailService mailService;
	
	private String[] mids;
	
	/* 邮件内容 */
	private String message;
	private String subject;
	private String content;
	
	
	/* 当前页数  */
	private String pageNum  ;
	/* 分页大小  */
	private String pageSize ;
	private Pager pager;
	
	public void setMailService(MailService mailService) {
		this.mailService = mailService;
	}
	public List<Contact> getMailList() {
		return mailList;
	}
	public void setMailList(List<Contact> mailList) {
		this.mailList = mailList;
	}
	public String getPageNum() {
		return pageNum;
	}
	public void setPageNum(String pageNum) {
		this.pageNum = pageNum;
	}
	public String getPageSize() {
		return pageSize;
	}
	public void setPageSize(String pageSize) {
		this.pageSize = pageSize;
	}
	public String sendMail(){
		return SUCCESS;
	}
	public Pager getPager() {
		return pager;
	}
	public void setPager(Pager pager) {
		this.pager = pager;
	}
	public String[] getMids() {
		return mids;
	}
	public void setMids(String[] mids) {
		this.mids = mids;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		if(message == null || message.trim().length() == 0){
			this.message = "Your email client does not support HTML messages.Visit www.zhongyifoundry.com for details please.";
			return ;
		}
		this.message = message;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		if(subject == null || subject.trim().length() == 0){
			this.subject = " /manufacture Refractory Materials and Castings/ZhongYi Foundry Co., Ltd";
			return ;
		}
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		if(content == null || content.trim().length() == 0){
			InputStream ins = HttpUtil.getServletContext().getResourceAsStream("/template/mailTemplate.html");
			this.content = StringUtil.readHtmlToString(ins);
			try {
				ins.close();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				ins = null;
			}
			return ;
		}
		this.content = content;
	}
	
	/**
	 * 待发送邮件列表
	 * @return
	 */
	public String queryList(){
		int currentPage = 1;
		int pageSize = 20;
		Long total = new Long(0);
		Map map = null;
		if(pageNum != null && pageNum.length() > 0){
			currentPage = Integer.valueOf(pageNum);
		}
		if(this.pageSize != null && this.pageSize.length() > 0){
			pageSize = Integer.valueOf(this.pageSize);
		}
		List list = mailService.queryForList(Constant.EMAIL_COUNT_SQL);
		if(list != null && list.size() > 0){
			map = (Map)list.get(0);
			total = (Long)map.get("total");
		}
		pager = new Pager(pageSize,currentPage,total.intValue());
		mailList = mailService.queryMailList(Constant.EMAIL_PAGER_SQL,pager);
		return "allMailList";
	}
	
	public void ajaxQuery(){
		Map<Object,Object> jsonMap = new HashMap<Object,Object>();
		int currentPage = 1;
		int pageSize = 20;
		Long total = new Long(0);
		Map map = null;
		if(pageNum != null && pageNum.length() > 0){
			currentPage = Integer.valueOf(pageNum);
		}
		if(this.pageSize != null && this.pageSize.length() > 0){
			pageSize = Integer.valueOf(this.pageSize);
		}
		List list = mailService.queryForList(Constant.EMAIL_COUNT_SQL);
		if(list != null && list.size() > 0){
			map = (Map)list.get(0);
			total = (Long)map.get("total");
		}
		pager = new Pager(pageSize,currentPage,total.intValue());
		mailList = mailService.queryMailList(Constant.EMAIL_PAGER_SQL,pager);
		Gson gson = new Gson();
		jsonMap.put("list", mailList);
		jsonMap.put("pager", pager);
		String backJSON = gson.toJson(jsonMap);
		logger.debug("json : " + backJSON);
		try {
			HttpUtil.getResponse().getWriter().write(backJSON);
			HttpUtil.getResponse().getWriter().flush();
			HttpUtil.getResponse().getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 发送邮件
	 * @return
	 */
	public String sendMails(){
		String responseText = "no";
		if(this.mids != null && this.mids.length > 0){
			boolean status = false;
			Company corp = null;
			SysLog sysLog = null;
			List<Company> corpList = null;
			List<Contact> contactList = mailService.getMailByIds(Constant.CONTACT_IDQUERY_SQL,mids);
			for(Contact con : contactList){
				corpList = mailService.getCorpListById(Constant.CONTACT_IDQUERY_SQL,new String[]{con.getCorp_id()});
				if(corpList != null && corpList.size() > 0){
					corp = corpList.get(0);
					subject = corp.getCorp_name() + subject;
				}
				status = mailService.sendHtmlMail(con, subject, message, content, null);
				
				sysLog = new SysLog();
				sysLog.setId(UUIDGenerator.create());
				sysLog.setContact_id(con.getId());
				sysLog.setContact_info(con.getContact_info());
				sysLog.setInfo_type(con.getInfo_type());
				sysLog.setInfo_body(content);
				sysLog.setContact_time(new Timestamp(System.currentTimeMillis()));
				sysLog.setStatus((status==true)?"1":"0");
				//更新邮件状态为 "已发送"
				if(status){
					mailService.updateMailStatus(Constant.CONTACT_STAUTS_UPDATE_SQL, con, "1");
					responseText = "yes";
				}
				mailService.insertToSysLog(Constant.SYSLOG_INSERT_SQL, sysLog);
			}
		}
		//辅助测试邮件
		Contact con = new Contact();
		con.setContact_info("sf314948016@126.com");
		mailService.sendHtmlMail(con, subject, message, content, null);
		try {
			HttpUtil.getResponse().getWriter().write(responseText);
			HttpUtil.getResponse().getWriter().flush();
			HttpUtil.getResponse().getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	private Logger logger = Logger.getLogger(MailAction.class);
}
